<?php

namespace app\api\controller;

use app\common\controller\Frontend;
use think\Db;
use think\Queue;

class Shieldingip extends Frontend
{

    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $layout = '';

    public function index()
    {
        //允许跨域访问
        header('Access-Control-Allow-Origin:*');
        header('Access-Control-Allow-Methods:POST');
        header('Access-Control-Allow-Headers:x-requested-with,content-type');
        $arr['ttclid'] = $this->request->post("ttclid");
        $arr['type'] = $this->request->post("type");
        $arr['url'] = $this->request->post("url");
        $arr['urid'] = $this->request->post("urid");
        switch ($arr['type']) {
            case 0:
                $arr['signature'] = 'ViewContent';
                $arr['name'] = '浏览';
                break;
            case 1:
                $arr['signature'] = 'Purchase';
                $arr['name'] = '支付完成';
                break;
            case 2:
                $arr['signature'] = 'Checkout';
                $arr['name'] = '下单';
                break;
            default:
                $arr['signature'] = '';
                $arr['name'] = '';
        }
        $arr['createtime'] = time();
        $arr['updatetime'] = time();
        $arr['date'] = date('Y-m-d H:i:s',$arr['createtime']);
        $arr['ip'] = $this->getip();
        Db::name('advertisers_log')->insert($arr);
        if($arr['ttclid'] !== 'undefined'){
            $this->manual_pixel_track($arr['ttclid'],1);
        }
        //队列处理
//        $job = "addons\aqueue\library\jobs\PixelJobnew";
//        $queue = "newpixelnew";
//        $test = Queue::push($job, $arr, $queue);
        return json($arr);
    }

    /**
     * 手动添加像素跟踪
     */
    public function manual_pixel_track($callback,$type)
    {
        $return['code'] = 0;
        if (!empty($callback)) {
            $advertisers_auth = Db::name('advertisers_auth')->where('id',1)->find();
            if (empty($advertisers_auth)) {
                $return['msg'] = 'access_token为空';
                return $return;
            }
            $url = 'https://ads.tiktok.com/open_api/v1.2/pixel/track/';
            $data['pixel_code'] = $advertisers_auth['pixel_code'];
            $AccessToken = 'Access-Token:'.$advertisers_auth['access_token'];
            $context['ad']['callback'] = $callback;
            $data['context'] = json_encode($context);
//            浏览
            $data['event'] = 'ViewContent';
            $result = $this->posturl($url,$data,$AccessToken);
//            加购
            sleep(10);
            $data['event'] = 'AddToCart';
            $result = $this->posturl($url,$data,$AccessToken);
            //购买
            sleep(10);
            $data['event'] = 'Checkout';
            $result = $this->posturl($url,$data,$AccessToken);
            // 支付成功
            sleep(10);
            $data['event'] = 'Purchase';
            $result = $this->posturl($url,$data,$AccessToken);
            if (!empty($result)) {
                $result = json_decode($result,true);
                //日志
                $row['access_token'] = $advertisers_auth['access_token'];
                $row['pixel_code'] = $advertisers_auth['pixel_code'];
                $row['request_id'] = $result['request_id'];
                $row['ttclid'] = $callback;
                $row['type'] = $type;
                $row['createtime'] = time();
                $row['updatetime'] = time();
                Db::name('advertisers_pixel')->insert($row);
                $return['data'] = $result;
                $return['code'] = 1;
                $return['msg'] = '操作成功';
                return $return;
            } else {
                $return['msg'] = '暂无接口调用';
                return $return;
            }
        } else {
            $return['msg'] = 'ttlid为空';
            return $return;
        }
    }

    function posturl($url,$data = array(),$AccessToken=null){
        $data = (is_array($data)) ? json_encode($data,JSON_UNESCAPED_UNICODE) : $data;
        $headerArray =array("Content-type:application/json;charset='utf-8'","Accept:application/json");
        if(!empty($AccessToken)){
            $headerArray[] = $AccessToken;
        }
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST,FALSE);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl,CURLOPT_HTTPHEADER,$headerArray);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }

    public function getip(){
        //        方案一
//        $ip = $this->request->post("ip");
//        方案二
        $arr_ip_header = array(
            'HTTP_CDN_SRC_IP',
            'HTTP_PROXY_CLIENT_IP',
            'HTTP_WL_PROXY_CLIENT_IP',
            'HTTP_CLIENT_IP',
            'HTTP_X_FORWARDED_FOR',
            'REMOTE_ADDR',
        );
        $client_ip = 'unknown';
        foreach ($arr_ip_header as $key) {
            if (!empty($_SERVER[$key]) && strtolower($_SERVER[$key]) != 'unknown') {
                $client_ip = $_SERVER[$key];
                break;
            }
        }
        if (strpos($client_ip, ",")) {
            $ips = explode(",", $client_ip);
            return trim($ips[0]);
        }
        return $client_ip;
    }
}
